<?php
/**
 * Created by PhpStorm.
 * User: zhou
 * Date: 20-1-12
 * Time: 上午10:19
 */

namespace App\Service\Query\Common;


trait CommonQuery
{
    /**
     * @var Model
     */
    protected $model;
    protected $offset;
    protected $limit;


    public function setWheres($where)
    {
        $this->model = $this->model->where($where);

        return $this;
    }

    /**
     *
     * @param $field
     * @param $value
     * @return $this|Model
     */
    public function whereIn($field, $value)
    {
        if (empty($value)) {
            return $this;
        }

        if (is_array($value) && count($value) == 1) {
            $value = array_pop($value);
            $this->model = $this->model->where($field, $value);
            return $this;
        }

        if (is_array($value)) {
            $this->model = $this->model->whereIn($field, $value);
            return $this;
        }

        $this->model = $this->model->where($field, $value);
        return $this;
    }

    protected function getOffsetAndLimit()
    {
        $request = \request();
        $page = $request->input('page',1);
        $this->limit = $request->input('limit',30);
        $this->offset = ($page-1)*$this->limit ;
    }

    public function getLists($field=['*'])
    {
        $this->getOffsetAndLimit();
        $lists = $this->model->offset($this->offset)
                             ->limit($this->limit)
                             ->get($field);

        return $lists;
    }

    public function getCounts()
    {
        return $this->model->count();
    }

    public function getListsAndCount($field=['*'],$orderField='id',$orderBy='desc')
    {
        $this->sort($orderField,$orderBy);

        return [
            'count' => $this->getCounts(),
            'lists' => $this->getLists($field),
        ];
    }

    //返回列表空数据
    protected function returnListsEmpty()
    {
        return [
            'count' => 0,
            'lists' => [] ,
        ];
    }


    protected function sort($field='id',$orderBy='desc')
    {
        $this->model = $this->model->orderBy($field,$orderBy);
    }


    /**
     * 获取全部
     */
    public function getAll($field=['*'])
    {
        return $this->model->all($field);
    }


    /**
     * 简化pluck到返回数组
     * @param $field
     * @param string $key
     * @return array
     */
    public function pluckToArray($field, $key = '')
    {
        if (empty($key)) {
            return $this->model->pluck($field)->toArray();
        } else {
            return $this->model->pluck($field, $key)->toArray();
        }
    }


}